<template>
  <AdaptiveNavBar title="我的" variant="transparent" :showBack="true" :showHome="true" />
  <!-- 固定在顶部的渐变背景 -->
  <view class="top-gradient-bg"></view>
  <view class="gradient-bg"></view>
  <view class="content-area" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
    <view class="mine-page">
      <!-- 用户信息区 -->
      <view class="user-info-section card"
        style="margin-bottom: 0rpx;border-radius: 0rpx;;border-top-left-radius: 24rpx;border-top-right-radius:24rpx ;box-shadow:none;">
        <view class="user-info">
          <!-- 使用新的微信头像选择方式 -->
          <button class="avatar-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <view class="avatar">
              <image v-if="hasAvatar" :src="displayAvatar" mode="aspectFill" @error="handleImageError"></image>
              <FontIcon v-else name="icon-mine" :size="80" color="#999"></FontIcon>
            </view>
          </button>
          <view class="user-meta">
            <!-- 昵称区域 - 点击获取微信昵称和手机号 -->
            <button class="user-info-button" open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
              <text class="user-name">{{ userInfo.nickname || '未设置昵称' }}</text>
            </button>
            <text class="user-nickname-display">{{ formatPhone(userInfo.phone) }}</text>
          </view>
        </view>
      </view>

      <!-- 昵称输入弹窗 -->
      <u-popup v-model="showNicknameInput" mode="center" :closeable="true" :close-on-click-overlay="true" @open="onNicknamePopupOpen">
        <view class="nickname-popup">
          <view class="popup-title">获取微信昵称</view>
          <view class="popup-tip">点击输入框，键盘上方会显示您的微信昵称，可直接选择</view>
          <input 
            ref="nicknameInput"
            class="nickname-input" 
            type="nickname" 
            v-model="inputNickname" 
            placeholder="请点击输入框选择微信昵称" 
            maxlength="20"
            @input="onNicknameInput"
            @confirm="handleGetNickname"
            @focus="onNicknameFocus"
          />
          <view class="popup-buttons">
            <button class="popup-btn cancel-btn" @click="showNicknameInput = false">取消</button>
            <button class="popup-btn confirm-btn" @click="handleGetNickname">确定</button>
          </view>
        </view>
      </u-popup>

      <!-- 快捷功能 -->
      <view class="quick-actions card"
        style="border-radius: 0rpx;;border-bottom-left-radius: 24rpx;border-bottom-right-radius:24rpx ;box-shadow:none;">
        <view class="action-item" v-for="action in quickActions" :key="action.id" @click="handleQuickAction(action)">
          <image v-if="action.image" :src="action.image" mode="aspectFit" class="action-icon"></image>
          <FontIcon v-else :name="action.icon" :size="action.size || 56" :color="action.color"></FontIcon>
          <text class="action-text">{{ action.text }}</text>
        </view>
      </view>

      <!-- 菜单 -->
      <view class="menu-section card">
        <view class="section-header">
          <text class="section-title">菜单</text>
        </view>
        <view class="menu-grid">
          <view class="menu-item" v-for="menu in menuItems" :key="menu.id" @click="handleMenuClick(menu)">
            <view class="menu-icon" :style="{ backgroundColor: menu.bgColor }">
              <FontIcon :name="menu.icon" :size="menu.size || 36" :color="menu.iconColor"></FontIcon>
            </view>
            <text class="menu-text">{{ menu.text }}</text>
          </view>
        </view>
      </view>

      <!-- 设置 -->
      <view class="settings-section card">
        <view class="section-header">
          <text class="section-title">设置</text>
        </view>
        <view class="settings-grid">
          <view class="setting-item" v-for="setting in settings" :key="setting.id" @click="handleSettingClick(setting)">
            <image v-if="setting.image" :src="setting.image" mode="aspectFit" class="setting-icon"></image>
            <FontIcon v-else :name="setting.icon" :size="setting.size || 36"></FontIcon>
            <text class="setting-text">{{ setting.text }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 自定义tabbar -->
    <CustomTabBar></CustomTabBar>
  </view>
</template>

<script>
import { switchTabBar, updateTabBarSelected, switchRole } from '@/utils/tabBarUtil';
import { ROLE_TYPE, HOME_ROUTE_MAP } from '@/config/app';
import { logout } from '@/utils/login';
import CustomTabBar from '@/components/CustomTabBar.vue';
import { useUserStore } from '@/store';

// 移除了重复导入的模块，并整理了导入顺序
export default {
  components: {
    CustomTabBar
  },
  computed: {
    hasAvatar() {
      return typeof this.userInfo?.avatar === 'string' && this.userInfo.avatar.trim() !== '';
    },
    displayNickname() {
      // 优先显示用户编辑的昵称，如果没有则显示微信昵称
      return this.userInfo.customName || this.userInfo.wechatName || '未设置昵称';
    },
    displayWechatName() {
      // 显示微信昵称
      return this.userInfo.wechatName || '未设置';
    },
    displayAvatar() {
      return this.userInfo.avatar || '';
    }
  },
  data() {
    return {
      // 用户数据
      userInfo: {
        avatar: '',
        id: '',
        nickname: '', // 缓存中的昵称（用于 user-name 显示）
        wechatName: '', // 微信获取的昵称
        phone: '',
        customName: '' // 用户编辑的昵称
      },
      // 昵称输入相关
      showNicknameInput: false,
      inputNickname: '',
      phoneCode: null, // 手机号授权码

      // 快捷功能
      quickActions: [
        { id: 1, text: '营员管理', icon: 'icon-renyuanguanli', image: '/static/myIcon/my-info.png', color: '#333', size: 56 },
        { id: 2, text: '规则中心', icon: 'icon-category', image: '/static/myIcon/my-guize.png', color: '#333', size: 56 },
        { id: 3, text: '网站公告', icon: 'icon-announcement', image: '/static/myIcon/my-gonggao.png', color: '#333', size: 56 },
        { id: 4, text: '消息通知', icon: 'icon-xiaoxi', image: '/static/myIcon/my-message.png', color: '#333', size: 56 }
      ],

      // 菜单项
      menuItems: [
        { id: 1, text: '订单', bgColor: '#FFF1E6', icon: 'icon-rule-center', iconColor: '#FF8A00', size: 48 },
        { id: 2, text: '收藏', bgColor: '#FFF3E0', icon: 'icon-shoucang', iconColor: '#FFB800', size: 48 },
        { id: 3, text: '营员照片', bgColor: '#E3F2FD', icon: 'icon-zhaopian', iconColor: '#007AFF', size: 48 },
        { id: 4, text: '意见反馈', bgColor: '#E8F5E9', icon: 'icon-consult', iconColor: '#34C759', size: 48 }
      ],

      // 设置项
      settings: [
        { id: 1, text: '提醒设置', icon: 'icon-tixingshezhi', image: '/static/myIcon/my-message2.png', size: 56 },
        { id: 2, text: '隐私管理', icon: 'icon-yinsiguanli', image: '/static/myIcon/my-yinsi.png', size: 56 },
        { id: 3, text: '商家端', icon: 'icon-merchant-entrance', image: '/static/myIcon/my-BO.png', size: 56 }
      ]
    };
  },

  onLoad() {
    // 页面加载时的初始化操作
    // 重置用户角色为普通用户
    this.resetUserRole();
  },

  onShow() {
    // 隐藏原生 tabbar，显示自定义 tabbar
    try {
      uni.hideTabBar({ animation: false });
    } catch (e) {
      // 忽略错误
    }
    // 设置当前tabBar选中项
    updateTabBarSelected.call(this, 3);

    // 加载用户信息
    this.loadUserInfo();
  },

  onReady() {
    // 页面初次渲染完成时触发
  },

  onHide() {
    // 页面隐藏时触发
  },

  onUnload() {
    // 页面卸载时触发
  },

  methods: {
    // 重置用户角色为普通用户
    resetUserRole() {
      try {
        const userStore = useUserStore();
        if (userStore) {
          // 将角色设置为普通用户
          userStore.setRole('user');
          console.log('用户角色已重置为普通用户');
        }
      } catch (error) {
        console.error('重置用户角色失败:', error);
      }
    },

    // 切换到商家端
    async switchToMerchant() {
      await switchTabBar('merchant');
    },

    // 加载用户信息
    loadUserInfo() {
      const info = uni.getStorageSync('userInfo');
      console.log('从存储加载的用户信息:', info);
      if (info) {
        // 使用 $set 确保响应式更新
        this.$set(this.userInfo, 'avatar', info.avatarUrl || info.avatar || '');
        this.$set(this.userInfo, 'id', info.id || '');
        // 从缓存中读取 nickname（用于 user-name 显示）
        this.$set(this.userInfo, 'nickname', info.nickname || '');
        // 微信昵称（wechatName）
        this.$set(this.userInfo, 'wechatName', info.wechatName || '');
        // 确保从 phone 字段取值
        this.$set(this.userInfo, 'phone', info.phone || '');
        this.$set(this.userInfo, 'customName', info.customName || '');
      }
      console.log('加载后的 this.userInfo', this.userInfo);
      console.log('手机号 phone 值:', this.userInfo.phone);
      console.log('nickname 值:', this.userInfo.nickname);
      
      // 强制更新视图，确保数据刷新
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 处理用户信息
    clickSetting() {
      uni.navigateTo({ url: `/public/customer/index?id=${this.userInfo.id}` });
    },

    // 处理获取手机号
    async handleGetPhoneNumber(e) {
      try {
        console.log('获取手机号事件:', e);
        
        // 检查是否授权成功
        if (e.detail.errMsg !== 'getPhoneNumber:ok') {
          console.log('用户取消手机号授权');
          uni.showToast({
            title: '需要授权才能获取手机号',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        const { code } = e.detail;
        console.log('手机号授权码:', code);

        // 保存手机号授权码，然后弹出昵称输入框
        this.phoneCode = code;
        this.showNicknameInput = true;
        
      } catch (error) {
        console.error('获取手机号失败:', error);
        uni.showToast({
          title: '获取失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 弹窗打开时自动聚焦输入框
    onNicknamePopupOpen() {
      this.$nextTick(() => {
        // 延迟一下，确保弹窗完全打开后再聚焦
        setTimeout(() => {
          // 尝试聚焦输入框，触发键盘显示微信昵称
          const query = uni.createSelectorQuery().in(this);
          query.select('.nickname-input').boundingClientRect((data) => {
            if (data) {
              console.log('输入框已定位，尝试聚焦');
            }
          }).exec();
        }, 300);
      });
    },

    // 输入框获得焦点时
    onNicknameFocus() {
      console.log('输入框获得焦点，键盘应该会显示微信昵称');
    },

    // 监听输入框输入事件
    onNicknameInput(e) {
      console.log('输入框内容变化:', e.detail.value);
      this.inputNickname = e.detail.value;
    },

    // 获取微信昵称（通过输入框）
    async handleGetNickname() {
      try {
        // 获取输入框中的昵称
        const nickname = this.inputNickname || '';
        
        if (!nickname) {
          uni.showToast({
            title: '请输入昵称',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        // 如果有手机号授权码，需要发送到后端解密
        let phone = '';
        if (this.phoneCode) {
          try {
            // 调用后端接口解密手机号
            const { request, BASE_URL } = await import('@/utils/request');
            const phoneResult = await request({
              url: `${BASE_URL}/wechat-auth/decode-phone`,
              method: 'POST',
              data: { phoneCode: this.phoneCode }
            });
            
            if (phoneResult.code === 200 && phoneResult.data && phoneResult.data.phone) {
              phone = phoneResult.data.phone;
              console.log('解密后的手机号:', phone);
            }
          } catch (phoneError) {
            console.warn('解密手机号失败:', phoneError);
            // 即使解密失败，也继续更新昵称
          }
        }

        // 更新本地用户信息
        this.$set(this.userInfo, 'wechatName', nickname);
        this.$set(this.userInfo, 'nickname', nickname);
        if (phone) {
          this.$set(this.userInfo, 'phone', phone);
        }

        // 更新本地存储
        const storedUserInfo = uni.getStorageSync('userInfo') || {};
        storedUserInfo.wechatName = nickname;
        storedUserInfo.nickname = nickname;
        if (phone) {
          storedUserInfo.phone = phone;
        }
        uni.setStorageSync('userInfo', storedUserInfo);

        // 关闭输入框
        this.showNicknameInput = false;
        this.inputNickname = '';
        this.phoneCode = null;

        // 强制更新视图
        await this.$nextTick();
        this.$forceUpdate();

        uni.showToast({
          title: '获取成功',
          icon: 'success',
          duration: 2000
        });

      } catch (error) {
        console.error('获取昵称失败:', error);
        uni.showToast({
          title: '获取失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 处理微信头像选择（新方式）
    async onChooseAvatar(e) {
      try {
        console.log('选择头像事件:', e);
        const { avatarUrl } = e.detail;
        
        if (!avatarUrl) {
          console.warn('未获取到头像路径');
          return;
        }

        // 头像路径已经是本地临时路径，可以直接使用
        let finalAvatarUrl = avatarUrl;
        
        // 更新本地用户信息
        this.$set(this.userInfo, 'avatar', finalAvatarUrl);
        
        // 更新本地存储的用户信息
        const storedUserInfo = uni.getStorageSync('userInfo') || {};
        storedUserInfo.avatar = finalAvatarUrl;
        storedUserInfo.avatarUrl = finalAvatarUrl;
        uni.setStorageSync('userInfo', storedUserInfo);

        console.log('更新后的头像路径:', finalAvatarUrl);

        // 强制更新视图
        await this.$nextTick();
        this.$forceUpdate();

        // 显示成功提示
        uni.showToast({
          title: '头像更新成功',
          icon: 'success',
          duration: 2000
        });

        // TODO: 如果需要同步到后端，可以在这里调用更新接口
        // await this.updateUserInfoToServer({
        //   avatarUrl: finalAvatarUrl
        // });
      } catch (error) {
        console.error('处理头像选择失败:', error);
        uni.showToast({
          title: '头像更新失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 处理图片加载错误
    handleImageError(e) {
      console.error('头像加载失败:', e);
      console.error('头像URL:', this.userInfo.avatar);
      // 如果图片加载失败，清空头像URL，显示默认图标
      this.$set(this.userInfo, 'avatar', '');
    },

    // 格式化手机号显示
    formatPhone(phone) {
      if (!phone || phone === '') {
        return '未绑定手机号';
      }
      // 确保 phone 是字符串
      const phoneStr = String(phone);
      // 如果是11位手机号，进行脱敏处理
      if (phoneStr.length === 11 && /^\d+$/.test(phoneStr)) {
        return phoneStr.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      }
      // 其他情况直接返回
      return phoneStr;
    },

    // 处理快捷操作
    handleQuickAction(action) {
      uni.showToast({ title: `进入${action.text}`, icon: 'none' });
      if (action.id === 1) {
        // 营员管理
        uni.navigateTo({ url: '/public/period/period' });
      } else if (action.id === 2) {
        // 规则中心
        uni.navigateTo({ url: '/public/ruleCenter/index' });
      } else if (action.id === 3) {
        // 网站公告
        uni.navigateTo({ url: '/public/notice/index' });
      } else if (action.id === 4) {
        // 消息通知
        uni.navigateTo({ url: '/public/message/index' });
      }
    },

    // 处理菜单点击
    handleMenuClick(menu) {
      if (menu.id === 1) {
        // 订单
        uni.navigateTo({ url: '/public/order/order' });
      } else {
        uni.showToast({ title: `进入${menu.text}`, icon: 'none' });
      }
    },

    // 处理设置点击
    handleSettingClick(item) {
      if (item.id === 3) {
        // 切换到商家端
        uni.showModal({
          title: '提示',
          content: '确定要切换到商家端吗？',
          success: async (res) => {
            if (res.confirm) {
              try {
                // 显示加载提示
                uni.showLoading({
                  title: '切换中...'
                });

                // 1. 切换角色
                const success = await switchRole(ROLE_TYPE.MERCHANT);

                if (success) {
                  // 2. 显示切换成功提示
                  uni.hideLoading();
                  uni.showToast({
                    title: '已切换到商家端',
                    icon: 'success',
                    duration: 1500
                  });

                  // 3. 跳转到商家端入口页面
                  setTimeout(() => {
                    uni.reLaunch({
                      url: '/public/login/merchantLogin/index',
                      success: () => {
                        console.log('切换到商家端入口成功');
                      },
                      fail: (err) => {
                        console.error('切换到商家端入口失败:', err);
                        uni.showToast({
                          title: '切换失败，请重试',
                          icon: 'none'
                        });
                      }
                    });
                  }, 1500);
                } else {
                  uni.hideLoading();
                  uni.showToast({
                    title: '切换失败，请重试',
                    icon: 'none'
                  });
                }
              } catch (e) {
                uni.hideLoading();
                console.error('切换角色失败:', e);
                uni.showToast({
                  title: '切换失败，请重试',
                  icon: 'none'
                });
              }
            }
          }
        });
      } else {
        // 其他设置项的处理逻辑
        console.log('点击了设置项:', item.text);
      }
    },

    // 处理退出登录
    handleLogout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 使用封装好的logout函数
            logout();
          }
        }
      });
    },
  }
};
</script>

<style lang="scss">
/* 固定在顶部的渐变背景 */
.top-gradient-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 334rpx;
  background: linear-gradient(180deg, #FC642F 0%, #FE9D5C 100%);
  z-index: -1;
  /* 确保背景在内容下方 */
}

.gradient-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: #f8f8f8;
  ;
  z-index: -2;
}

.content-area {
  // background-color: #F8F8F8;
}

.mine-page {
  padding-bottom: 120rpx;
  /* 为自定义tabbar留出空间 */
  width: 100%;
  min-height: 100vh;
  // background-color: #F8F8F8;
  padding: 1rpx 0 0 0;
}

/* 用户信息样式 */
.user-info-section {
  margin: 24rpx;
  /* 与主页保持一致的外边距 */
  padding: 24rpx 24rpx 0rpx 32rpx;
}

.user-info {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #E9E9E9;
  padding-bottom: 24rpx;
}

.avatar-button {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
  font-size: 0;
  display: inline-block;
}

.avatar-button::after {
  border: none;
}

.avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  margin-right: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.avatar:active {
  opacity: 0.7;
}

.avatar image {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  object-fit: cover;
}

.user-meta {
  flex: 1;
}

.user-id {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 8rpx;
  line-height: 1.4;
}

.user-name {
  font-size: 36rpx;
  font-weight: 700;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
  line-height: 1.4;
}

.user-nickname-display {
  font-size: 26rpx;
  color: #666666;
  display: block;
  line-height: 1.4;
}

.user-info-button {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  line-height: 1;
  font-size: 0;
  display: inline-block;
  text-align: left;
}

.user-info-button::after {
  border: none;
}

/* 昵称输入弹窗样式 */
.nickname-popup {
  width: 600rpx;
  padding: 40rpx;
  background-color: #fff;
  border-radius: 24rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 20rpx;
}

.popup-tip {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  margin-bottom: 30rpx;
  line-height: 1.5;
}

.nickname-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 30rpx;
  box-sizing: border-box;
}

.nickname-input:focus {
  border-color: #007aff;
}

.popup-buttons {
  display: flex;
  gap: 20rpx;
}

.popup-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
}

.logout-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logout-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

/* 快捷功能样式 */
.quick-actions {
  margin: 0 24rpx 24rpx 24rpx;
  /* 与主页保持一致的外边距 */
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 25%;
}

.action-icon {
  width: 48rpx;
  height: 48rpx;
}

.action-text {
  font-size: 26rpx;
  color: #333;
  margin-top: 16rpx;
}

/* 菜单区域样式 */
.menu-section {
  margin: 0 24rpx 24rpx 24rpx;
  /* 与主页保持一致的外边距 */
  overflow: hidden;
}

.section-header {
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.menu-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 32rpx 0;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 25%;
}

.menu-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.menu-text {
  font-size: 26rpx;
  color: #333;
}

/* 设置区域样式 */
.settings-section {
  margin: 0 24rpx 24rpx 24rpx;
  /* 与主页保持一致的外边距 */
  overflow: hidden;
}

.settings-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 32rpx 0;
}

.setting-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 33.33%;
}

.setting-icon {
  width: 40rpx;
  height: 40rpx;
}

.setting-text {
  font-size: 26rpx;
  color: #333;
  margin-top: 16rpx;
}

/* 通用卡片样式 - 与主页保持一致 */
.card {
  background: white;
  border-radius: 24rpx;
  /* 与主页保持一致的圆角 */
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  /* 与主页保持一致的阴影 */
}
</style>